﻿using System;
using System.Collections.Generic;
using System.IO;
using Amazon.Glacier.Model;
using Newtonsoft.Json.Linq;

namespace AmazonGlacierGUI.Core.Helpers.AmazonGlacier
{
    //07-Sep-2012 Priyan R
    public class AmazonGlacierHelper : AmazonGlacierHelperBase
    {

        public List<VaultDetails> GetVaults(AmazonRegionEnum region)
        {
            try
            {
                InitClient();
                var response = _client.ListVaults(new ListVaultsRequest());
                var ret = new List<VaultDetails>();
                foreach (var res in response.ListVaultsResult.VaultList)
                {

                    ret.Add(new VaultDetails()
                    {
                        VaultARN = res.VaultARN,
                        Region = region,
                        NumberOfArchives = res.NumberOfArchives,
                        VaultName = res.VaultName,
                        TotalSize = res.SizeInBytes
                    });
                }
                return ret;

            }
            catch (Exception ex)
            {
                throw new Exception(GetExceptionMessage(ex));
            }
        }
        public void CreateNewVault(string vaultName)
        {
            try
            {
                InitClient();
                _client.CreateVault(new CreateVaultRequest() { VaultName = vaultName });
            }
            catch (Exception ex)
            {
                throw new Exception(GetExceptionMessage(ex));
            }
        }
        public void DeleteArchive(string archiveId)
        {
            try
            {
                InitClient();
                _client.DeleteArchive(new DeleteArchiveRequest()
                                          {
                                              ArchiveId = archiveId,
                                              VaultName = VaultName
                                          });
                
            }
            catch (Exception ex)
            {
                throw new Exception(GetExceptionMessage(ex));
            }
        }
        public string RequestInventory()
        {
            try
            {
                InitClient();
                InitiateJobRequest request = new InitiateJobRequest()
                                                 {
                                                     VaultName = VaultName,
                                                     JobParameters = new JobParameters()
                                                                         {
                                                                             Type = "inventory-retrieval"
                                                                         }
                                                 };
                InitiateJobResponse initJobResponse = _client.InitiateJob(request);
                return initJobResponse.InitiateJobResult.JobId;
            }
            catch (Exception ex)
            {
                throw new Exception(GetExceptionMessage(ex));
            }
        }
        public JobStatusResult GetJobStatus(string jobId)
        {
            try
            {
                InitClient();
                var res = new JobStatusResult();
                var resp = GetDescribeJobResponse(jobId);
                res.IsCompleted = resp.DescribeJobResult.Completed;
                return res;
            }
            catch (Exception ex)
            {
                throw new Exception(GetExceptionMessage(ex));
            }

        }
        
        /* JSON format
         {
   "VaultARN":"arn:aws:glacier:us-east-1:*****:vaults/****",
   "InventoryDate":"2012-09-25T06:10:24Z",
   "ArchiveList":[
      {
         "ArchiveId":"************",
         "ArchiveDescription":"key.txt",
         "CreationDate":"2012-09-24T15:44:28Z",
         "Size":161,
         "SHA256TreeHash":"bc4d96cb049dca043c365bec2a4ef119c7a51b86d1bbfdce0d828062c3ae5806"
      },
      {
         "ArchiveId":"*******",
         "ArchiveDescription":"sds",
         "CreationDate":"2012-09-24T15:48:13Z",
         "Size":161,
         "SHA256TreeHash":"bc4d96cb049dca043c365bec2a4ef119c7a51b86d1bbfdce0d828062c3ae5806"
      },
         */
        public VaultInventory GetVaultInventory(string jobId)
        {
            InitClient();
            var ret = new VaultInventory();
            var getJobOutputRequest = new GetJobOutputRequest()
            {

                JobId = jobId,
                VaultName = VaultName
            };
            GetJobOutputResponse getJobOutputResponse = _client.GetJobOutput(getJobOutputRequest);
            GetJobOutputResult result = getJobOutputResponse.GetJobOutputResult;
            using (Stream webStream = result.Body)
            {
                byte[] buffer = new byte[65536];
                var output = new MemoryStream();
                int length;
                while ((length = result.Body.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, length);
                }
                output.Flush();
                output.Seek(0, SeekOrigin.Begin);
                buffer = new byte[output.Length];
                output.Read(buffer, 0, buffer.Length);
                var jsonText = System.Text.Encoding.UTF8.GetString(buffer);
                var json = JObject.Parse(jsonText);
                ret.InventoryDate = DateTime.Parse((String) json["InventoryDate"]);
                ret.VaultARN = (String)json["VaultARN"];
                foreach (var archive in (JArray)json["ArchiveList"])
                {
                    ret.ArchiveDetails.Add(new ArchiveDetail()
                                               {
                                                   ArchiveId = archive["ArchiveId"].ToString(),
                                                   Description = archive["ArchiveDescription"].ToString(),
                                                   Size = long.Parse(archive["Size"].ToString()),
                                                   SHA256TreeHash =archive["SHA256TreeHash"].ToString(),
                                                   CreatedOn = DateTime.Parse(archive["CreationDate"].ToString())
                                               });
                }
            }
            return ret;
        }
    }

}
